package com.young.operation.components;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;

/**
 * 可调整的配置
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class HighAvailableDruidConfig {
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    private String connectionProperties;
    private int initialSize;
    private int maxActive = 10;
    private int minIdle = 0;
    private long maxWait = -1L;
    private String validationQuery;
    private int validationQueryTimeout = 10;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean testWhileIdle;
    private int maxPoolPreparedStatementPerConnectionSize = 20;
    private int queryTimeout = 120;
    private int transactionQueryTimeout = 120;
    private long timeBetweenEvictionRunsMillis;
    private long minEvictableIdleTimeMillis;
    private long maxEvictableIdleTimeMillis;
    private long timeBetweenConnectErrorMillis = 60;
    private String filters;
    private Boolean useGlobalDataSourceStat = true;

    private Properties connectProperties = new Properties();

    public Properties getConnectProperties() {
        if (null != connectionProperties && connectionProperties.trim().length() != 0) {
            String[] entries = connectionProperties.split(";");
            Properties properties = new Properties();

            for (String entry : entries) {
                if (entry.length() > 0) {
                    int index = entry.indexOf(61);
                    if (index > 0) {
                        String name = entry.substring(0, index);
                        String value = entry.substring(index + 1);
                        properties.setProperty(name, value);
                    } else {
                        properties.setProperty(entry, "");
                    }
                }
            }

            this.setConnectProperties(properties);
        } else {
            this.setConnectProperties(null);
        }
        return connectProperties;
    }

    public void setConnectProperties(Properties connectProperties) {
        if (null == connectProperties) {
            connectProperties = new Properties();
        }
        if (null != this.connectProperties) {
            this.connectProperties.putAll(connectProperties);
        } else {
            this.connectProperties = connectProperties;
        }
    }

}
